<template>
	<view class="font28 col-main">
		<fa-navbar title="编辑资产"></fa-navbar>
		<u-gap height="30" bg-color="#F6F8FB"></u-gap>
		<view class="form-gap"><text>扫码结果</text></view>
		<u-row gutter="0" class="b-none" v-for="(item, index) in TIDList" :key="index">
			<u-col span="3">
				<view v-if="index === 0">
					<text class="tip-dot">*</text>
					<text>标签ID</text>
				</view>
			</u-col>
			<u-col span="9" class="text-ellipsis"><text>{{item}}</text></u-col>
		</u-row>
		<view class="pb-m2"></view>
		<u-gap height="30" bg-color="#F6F8FB"></u-gap>
		<view class="form-gap">
			<text>资产信息</text>
		</view>
		<u-row gutter="0">
			<u-col span="3"><text class="tip-dot col-white">*</text><text class="col-main">资产ID</text></u-col>
			<u-col span="9"><u-input placeholder="" disabled v-model="formData.EpcId" /></u-col>
		</u-row>
		<u-row gutter="0">
			<u-col span="3">
				<view class="col-main">
					<text class="tip-dot">*</text>
					<text>资产名称</text>
				</view>
			</u-col>
			<u-col span="7.5"><u-input :clearable="false" v-model="formData.name" placeholder="请输入名称（20字符以内）" maxlength="20" /></u-col>
			<u-col span="1.5" class="text-right"><view class="float-right"><u-image @click="startVoiceInput(1)" width="48" height="48" src="/static/images/icon_voice@2x.png"></u-image></view></u-col>
		</u-row>
		<u-row gutter="0">
			<u-col span="3">
				<view class="col-main">
					<text class="tip-dot">*</text>
					<text>资产类型</text>
				</view>
			</u-col>
			<u-col span="7.5"><u-input v-model="input.category" :disabled="true" placeholder="请选择类型" @click="chooseCategory" /></u-col>
			<u-col span="1.5" class="text-right"><fa-icon name="icon-Right" color="#adadad" size="36" @click="chooseCategory" /></u-col>
		</u-row>
		<u-row gutter="0">
			<u-col span="3">
				<view class="col-main">
					<text class="tip-dot">*</text>
					<text>所属房产</text>
				</view> 
			</u-col>
			<u-col span="7.5"><u-input v-model="input.assets" :disabled="true" placeholder="请选择房产" /></u-col>
		</u-row>
		<u-row gutter="0" class="b-none" align="top">
			<u-col span="3" class="pt-m1">
				<text class="tip-dot col-white">*</text>
				<text class="col-main">图片</text>
			</u-col>
			<u-col span="9">
				<u-row class="b-none m-0">
					<u-col span="4" v-for="(item, index) in selectedFileList" :key="index" class="pos-re">
						<u-image width="100%" height="156" border-radius="8" :src="item.Url"></u-image>
						<!-- <fa-icon name="icon-guanbi" class="rm-icon" size="40" @click="() => selectedFileList.splice(index, 1)" /> -->
						<i class="rm-icon" @click="() => selectedFileList.splice(index, 1)"></i>
					</u-col>
					<u-col span="4" v-show="selectedFileList.length < 3">
						<fa-image-chooser size="normal" @choose="fileUpload" :maxCount="maxCount"/>
					</u-col>
				</u-row>
			</u-col>
		</u-row>
		<u-gap height="30" bg-color="#F6F8FB"></u-gap>
		<view class="form-gap flex-vertical-center" style="height: 100rpx;">
			<text class="pr-m2 pt-m1">描述</text><u-image @click="startVoiceInput(2)" width="48" height="48" src="/static/images/icon_voice@2x.png"></u-image>
		</view>
		<u-row class="over-hid b-r10 p-0" style="border: 1px solid #E8E8E8;">
			<u-col class="px-m2 pb-m2">
				<u-input type="textarea" :customStyle="{'color': '#4F5053'}" :autoHeight="false" v-model="describe" @input="changeTextarea" height="116" :maxlength="maxlength" :clearable="false"></u-input>
				<view class="col-gray text-right pt-m1"><text>{{describe.length}}/500</text></view>
			</u-col>
		</u-row>
		<u-gap height="200" bg-color="#ffffff"></u-gap>
		<view class="pos-fix p-2 bg-ff fullwidth" style="bottom: 0;">
			<u-button
				class="btn-grad"
				:type="!formValid ? 'default' : 'primary'"
				:class="formValid ? '' : 'btn-disable2'"
				:disabled="!formValid"
				shape="circle"
				@click="upDateAsset">
				保存
			</u-button>
		</view>
	</view>
</template>

<script>
	import faNavbar from '@/components/fa-navbar/fa-navbar.vue'
	import FaImageChooser from '@/components/fa-image-chooser/fa-image-chooser.vue'
	import FaIcon from '@/components/fa-icon/fa-icon.vue'
	import permission from '../../util/permission.js'
	export default {
		components: {FaImageChooser, FaIcon, faNavbar},
		data() {
			return {
				// 扫描到的TID
				TIDList: [],
				// 表单数据
				formData: {
					Guid: "",
					EpcId: "",
					name: "",
					categoryId: "",
					assetsId: "",
					describe: ""
				},
				describe: '',
				input: {
					assets: "",
					category: "", // 页面上显示的分类格式：  一级分类-二级分类
				},
				// 选中的文件列表
				selectedFileList: [],
				show: {
					category: false,
					assets: false
				},
				selectedCategory: {},
				maxCount: 3,
				maxlength: -1,
				inputTarget: 1,
			};
		},
		onLoad(options) {
			this.formData.Guid = options.id;
			this.getAssetDetail();
			
			uni.$on('onChooseAssets', choose => {
				this.formData.assetsId = choose.ID;
				this.input.assets = choose.OrgName;
			});
			uni.$on('onChooseCategory', ({parent, children}) => {
				if (children) {
					// 有子级分类；
					this.input.category = `${parent.DictItemValue}-${children.DictItemValue}`;
					this.formData.categoryId = children.DictItemKey;
				} else {
					this.input.category = parent.DictItemValue;
					this.formData.categoryId = parent.DictItemKey;
				}
				this.selectedCategory = {parent, children};
			});
		},
		onUnload() {
			uni.$off('onChooseAssets');
			uni.$off('onChooseCategory');
		},
		computed: {
			// 表单检验
			formValid() {
				return this.TIDList.length > 0 && 
					this.formData.name.length > 0 && 
					this.formData.assetsId.length > 0 && 
					this.formData.categoryId.length > 0;
			}
		},
		watch: {
			// 动态更改图片可选数量
			selectedFileList() {
				this.maxCount = 3 - this.selectedFileList.length;
			},
			
			// 监听粘贴内容是否超出最大长度
			describe(nval, oval) {
				if (nval.length > 500) {
					this.describe = this.describe.slice(0, 500);
				}
			},
		},
		methods: {
			// 兼容iOS iOS计数时出现不一致的行为，未到500却不能输入了，动态控制maxlength
			changeTextarea(e) {
				e.length > 499 ? this.maxlength = 500 : this.maxlength = -1
			},
			
			// 获取资产详情
			getAssetDetail() {
				this.$api.getAssetDetail({ID: this.formData.Guid})
					.then(res => {
						if (res.code == 0) {
							this.TIDList = res.data.Tids;
							this.formData.EpcId = res.data.EpcId;
							this.describe = res.data.Description;
							this.describe.length > 499 ? this.maxlength = 500 : this.maxlength = -1;
							this.formData.name =  res.data.Name;
							this.input.assets = res.data.OrgName;
							this.formData.assetsId = res.data.OrgGuid;
							this.formData.categoryId = res.data.Type;
							this.selectedFileList = res.data.Pics;
							if (res.data.Type.split("_").length == 3) {
								this.input.category = res.data.TypeText;
								this.selectedCategory = {
									parent: { DictItemKey: res.data.Type }
								}
							} else {
								this.searchParentLevel(res.data.Type);
							}
						}
					})
					.catch(err => console.error(err))
			},
			
			// 查找二级类型对应的一级类型
			searchParentLevel(type) {
				let params = {
					ParentKey: 'ASSET_TYPE',
					PageIndex: 1,
					PageSize: 10000
				}
				this.$api.getTypeStatusList(params)
					.then(res => {
						if (res.code == 0) {
							let data = res.data.Data.find(item => type == item.DictItemKey)
							this.selectedCategory = {
								parent: { DictItemKey: data.DictTypeKey },
								children: { DictItemKey: data.DictItemKey },
							}
							this.input.category = `${data.DictTypeValue}-${data.DictItemValue}`;
						}
					})
					.catch(err => console.error(err))
			},
			
			// 上传文件
			fileUpload(fileList) {
				uni.showLoading({title: '上传中'});
				this.$api.uploadFile(fileList).then(res => {
					let filePath = JSON.parse(res).data[0].FilePath;
					this.selectedFileList.push({Url: filePath});
					uni.hideLoading();
				}).catch(err => {
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
					uni.hideLoading();
				});
			},

			// 选择房产
			chooseAssets() {
				let url = "../chooseAssets/chooseAssets";
				if (this.formData.assetsId) {
					url += `?selectedId=${this.formData.assetsId}`;
				}
				uni.navigateTo({url});
			},
			
			// 选择分类
			chooseCategory() {
				let url = "./chooseCategory/chooseCategory";
				if (this.selectedCategory.parent) {
					url += `?parentItemKey=${this.selectedCategory.parent.DictItemKey}`;
					if (this.selectedCategory.children) {
						url += `&childrenItemKey=${this.selectedCategory.children.DictItemKey}`;
					}
				}
				uni.navigateTo({url});
			},
			
			upDateAsset() {
				uni.showLoading({title: '提交中'});
				let data = {
					"Guid": this.formData.Guid,
					"Name": this.formData.name,
					"EpcId": this.formData.EpcId,
					"Tids": this.TIDList,
					"Description": this.describe,
					"OrgGuid": this.formData.assetsId,
					"Type": this.formData.categoryId,
					"Pics": this.selectedFileList.map(file => {return {"Guid": "", "Url": file.Url}})
				}
				this.$api.upDateAsset(data).then(res => {
					uni.hideLoading();
					if (res.code === 0) {
						uni.hideToast();
						uni.showToast({
							title: '提交成功'
						})
						setTimeout(() => { uni.navigateBack() }, 800);
					} else {
						uni.showToast({
							title: '提交失败，请稍后再试',
							icon: 'none'
						})
					}
				}).catch(err => console.error(err));
			},
			async startVoiceInput(target) {
				if (target !== 3)  {
					if (target === 1) {
						if (this.formData.name.length >= 20) {
							uni.showToast({title: "不可超过20个字符", icon: "none"});
							return;
						}
					}
					if (target === 2) {
						if (this.describe.length >= 500) {
							uni.showToast({title: "不可超过500个字符", icon: "none"});
							return;
						}
					}
					this.inputTarget = target;
				}
				let status = await this.checkPermission();
				if (status !== 1) {
					return;
				}

				this.startRecognize(read => {
					// 录入资产名称
					if (this.inputTarget === 1) {
						if (this.formData.name.length + read.length <= 20) {
							this.formData.name += read;
						} else {
							uni.showToast({title: "内容超出了字数限制", icon: 'none'});
						}
					} else {  // 2  录入资产描述
						if (this.describe.length + read.length <= 500) {
							this.describe += read;
						} else {
							uni.showToast({title: "内容超出了字数限制", icon: 'none'});
						}
					}
				});
			},
			startRecognize(_callback) {
				let options = {
					engine: 'baidu'
				};
				plus.speech.startRecognize(options, _callback);
			},
			async checkPermission() {
			    let status = permission.isIOS ? await permission.requestIOS('record') :
			        await permission.requestAndroid('android.permission.RECORD_AUDIO');
			    if (status === null || status === 1) {
			        status = 1;
			    } else if (status === 2) {
			        uni.showModal({
			            content: "系统麦克风已关闭",
			            confirmText: "确定",
			            showCancel: false,
			            success: function(res) {
			            }
			        })
			    } else {
			        uni.showModal({
			            content: "需要麦克风权限",
			            confirmText: "设置",
			            success: function(res) {
			                if (res.confirm) {
			                    permision.gotoAppSetting();
			                }
			            }
			        })
			    }
			    return status;
			}
		}
	}
</script>

<style lang="scss" scoped>
.form-gap {
	color: #2A2A2A;
	height: 80rpx;
	font-size: 36rpx;
	font-weight: bold;
	padding: 0 40rpx;
	line-height: 80rpx;
}
.u-row {
	padding: 16rpx 0;
	margin: 0 40rpx;
	border-bottom: 1px solid #ECECF0;
}
.u-hairline-border::after {
	border: none;
}
.rm-icon {
	position: absolute;
	top: -14rpx;
	right: 0;
	width: 40rpx;
	height: 40rpx;
	background: url(../../static/images/pic_close.svg) no-repeat;
}
.tip-dot {
	color: #E55D5D;
	padding-right: 6rpx;
}
.voice {
	width: 100%;
	height: 100%;
	background: #101B4E;
	position: relative;
	.voice-title {
		font-size: 32rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 600;
		color: #FFFFFF;
		display: flex;
		height: 90rpx;
		line-height: 90rpx;
	}
	.voice-gap{
		width: 560rpx;
		margin: 0 auto;
		height: 2px;
		background: linear-gradient(90deg, rgba(137, 205, 249, 0) 0%, #509EF0 54%, rgba(81, 159, 240, 0) 100%);
	}
	.voice-btn {
		width: 80%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		position: absolute;
		bottom: 20rpx;
		left: 10%;
		background: linear-gradient(310deg, #5BABF4 0%, #2E73E5 100%);
		border-radius: 40rpx;
		font-size: 32rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
	}
}
</style>